﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Itenso.TimePeriod;
using LogManager.Base.Data;
using LogManager.ViewModels.Filter;

namespace LogManager.Controllers
{
    public class StatisticController : BaseController
    {
        private IEventService _eventService;
        private ILogService _logService;

        public StatisticController(IEventService eventService, ILogService logService)
        {
            _eventService = eventService;
            _logService = logService;
        }
        
        public ActionResult EventsPerDay()
        {
            var model = new EventDateFilterViewModel();
            return View(model);
        }

        [HttpPost]
        public JsonResult EventsPerDayData(DateTime? start,DateTime? end)
        {
            //Create tree out of flat objects
            var eventsPerDay = from e in _eventService.GetEventsPerDate()
                               group e by e.LogName into g
                               select new {name = g.Key, data = g.Select(e => new {date = e.Date, count = e.Count})}; 
            
            return Json(eventsPerDay, JsonRequestBehavior.AllowGet);
        }

        public ActionResult EventsPerLogPercentage()
        {
            var model = new EventDateFilterViewModel();
            return View(model);
        }

        public ActionResult EventsPerLogColumn()
        {
            return View();
        }

        public JsonResult EventsPerLogColumnData()
        {
            var months = new List<DateTime>();
            DateTime month = DateTime.Now;
            do
            {
                months.Insert(0,month);
                month = month.AddMonths(-1);
            } while (month > DateTime.Now.AddMonths(-12));

            var series =
                from e in _eventService.GetEventsPerDate()
                group e by new { LogName = e.LogName }
                    into g
                    select new { name = g.Key.LogName, data = g.GroupBy(s => s.Date.Month).Select(s => new { month = s.Key, count = s.Sum(x => x.Count) }) };
            
            var data = new { categories = months.Select(m => new {text = m.ToString("MMM"), val = m.Month}), series =  series};
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public JsonResult EventsPerLogPercentageData()
        {
            //Extra select for js output
            var eventsPerLog = _eventService.GetEventsPerLog();
            decimal total = eventsPerLog.Sum(e => e.Count);
            var model = eventsPerLog.Select(e => new { name = e.LogName, percentage = (decimal)e.Count / total });
            
            return Json(model, JsonRequestBehavior.AllowGet);
        }
    }
}